import os
import re
import sys
from optparse import OptionParser

# set args to accept
parser = OptionParser()  
parser.add_option("-d","--folder", dest="base_dir", help="help") 
parser.add_option("-f","--file_filter", dest="file_filter", help="help") 
parser.add_option("-o", "--oldstr", dest="fromstr", help="help", metavar="String") 
parser.add_option("-n", "--newstr", dest="tostr", help="help", metavar="String") 
(options, args) = parser.parse_args() 
print 'options',options
print 'args',args

# global vars
scan_file_count = 0
replace_file_count = 0
line_count = 0

# check args
base_dir = options.base_dir
file_filter =options.file_filter
fromstr = options.fromstr
tostr = options.tostr
if base_dir is None:
    base_dir = '.'
if file_filter is None:
    file_filter = '*'

file_filter_parttern = '^' + file_filter.replace('.',r'\.').replace('*','.*') + '$'
print 'file_filter_parttern',file_filter_parttern

# replace all file
for dirpath, dirname, filenames in os.walk(base_dir):#Getting a list of the full paths of files
    for fname in filenames:
        if re.match(file_filter_parttern, fname):  
            scan_file_count += 1      
            path = os.path.join(dirpath, fname) #Joining dirpath and filenames            
            
            # show match lines count
            strg = open(path).read()
            count = len(re.findall(fromstr,strg))
            print path,':',count
            line_count += count
            if count > 0:
                replace_file_count += 1

            # display string in a file
            if 'find' in args:
                for line in open(path):
                    if fromstr in line:
                        print ' -',line, ' +',line.replace(fromstr,tostr)

            # replace string in a file
            if 'replace' in args:
                strg = open(path).read() #Opening the files for reading only
                if re.search(fromstr, strg):#If we find the pattern ....
                    #print path, strg
                    strg = strg.replace(fromstr, tostr) #We will create the replacement condistion
                    f = open(path, 'w') #We open the files with the WRITE option
                    f.write(strg) # We are writing the the changes to the files
                    f.close() #Closing the files

print 'scan file:',scan_file_count
print 'replace file:',replace_file_count
print 'replace line:',line_count




